<template>
  <div class="interface-pool-container">
    <!-- 搜索和操作栏 -->
    <div class="operation-bar">
      <el-button type="primary" @click="handleCreate" icon="el-icon-plus">新建接口</el-button>
      <el-input
          v-model="searchKey"
          placeholder="搜索接口池"
          prefix-icon="el-icon-search"
          clearable
          @keyup.enter.native="handleSearch"
          style="width: 300px; margin-left: 20px"
      >
        <el-button slot="append" icon="el-icon-search" @click="handleSearch"></el-button>
      </el-input>
    </div>

    <!-- 数据表格 -->
    <el-table
        :data="appList"
        stripe
        style="width: 100%"
        v-loading="loading"
    >
      <!-- 接口池名称列分配更多空间 -->
      <el-table-column
          prop="name"
          label="接口名称"
          width="180"
      >
        <template slot-scope="{ row }">
          <span>{{ row.name }}</span>
        </template>
      </el-table-column>

      <!-- 接口池名称列分配更多空间 -->
      <el-table-column
          prop="api"
          label="接口地址"
          min-width="200"
      >
        <template slot-scope="{ row }">
          <span>{{ row.api }}</span>
        </template>
      </el-table-column>

      <el-table-column
          prop="method"
          label="接口方法"
          width="100"
      />


      <!-- 更新时间列 -->
      <el-table-column
          prop="updateTime"
          label="更新时间"
          width="200"
      />

      <!-- 负责人列 -->
      <el-table-column
          prop="creator"
          label="创建人"
          width="120"
      />

      <!-- 负责人列 -->
      <el-table-column
          prop="remark"
          label="说明"
          width="200"
      />


      <!-- 操作列固定最小宽度 -->
      <el-table-column
          label="操作"
          :min-width="200"
          align="center"
      >
        <template slot-scope="{ row }">
          <el-button size="mini" @click="handleEdit(row)">编辑</el-button>
          <el-button
              size="mini"
              type="danger"
              @click="handleDelete(row)"
              icon="el-icon-delete"
          ></el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next"
        :total="total"
        style="margin-top: 20px"
    />

    <!-- 编辑弹窗 -->
    <el-dialog
        :title="isEdit ? '编辑接口' : '新建接口'"
        :visible.sync="dialogVisible"
        width="600px"
    >
      <el-form :model="createAppForm" :rules="rules" ref="form" label-width="100px">
        <el-form-item label="接口名称" prop="name">
          <el-input v-model="createAppForm.name" placeholder="请输入接口名称"/>
        </el-form-item>

        <el-form-item label="接口地址" prop="name">
          <el-input v-model="createAppForm.api" placeholder="请输入接口地址"/>
        </el-form-item>

        <el-form-item label="接口方法" prop="method">
          <el-select v-model="createAppForm.method" placeholder="请选择接口方法">
            <el-option
              v-for="item in methodOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="描述信息">
          <el-input
              v-model="createAppForm.remark"
              type="textarea"
              :rows="3"
              placeholder="请输入描述信息"
          />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmSubmit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {queryApiPage, createApi, updateApi, delApi} from '@/api/gateway-api'

export default {
  data() {
    return {
      searchKey: '',
      currentPage: 1,
      pageSize: 10,
      total: 40,
      loading: false,
      dialogVisible: false,
      isEdit: false,
      createAppForm: {
        api: null,
        name: '',
        remark: '',
        method: '' // 添加method字段的初始值
      },
      rules: {
        name: [{required: true, message: '名称不能为空', trigger: 'blur'}],
        envType: [{required: true, message: '请选择环境类型', trigger: 'change'}],
        method: [{required: true, message: '请选择接口方法', trigger: 'change'}] // 添加method的验证规则
      },
      // 模拟数据
      appList: [],
      statusMap: {
        0: {label: '未启用', type: 'info'},
        1: {label: '运行中', type: 'success'},
        2: {label: '已停用', type: 'danger'}
      },
      envTagType: {
        DEV: 'warning',
        TEST: 'primary',
        PROD: 'success'
      },
      envOptions: [
        {value: 'DEV', label: '开发环境'},
        {value: 'TEST', label: '测试环境'},
        {value: 'PROD', label: '生产环境'}
      ],
      methodOptions: [
        { value: 'ALL', label: 'ALL' },
        { value: 'GET', label: 'GET' },
        { value: 'POST', label: 'POST' },
        { value: 'PUT', label: 'PUT' },
        { value: 'DELETE', label: 'DELETE' },
        { value: 'HEAD', label: 'HEAD' },
        { value: 'PATCH', label: 'PATCH' },
        { value: 'OPTIONS', label: 'OPTIONS' }
      ],
    }
  },
  mounted() {
    this.loadAppData()
  },
  computed: {
    // filteredData() {
    //   return this.tableData.filter(item =>
    //       item.name.toLowerCase().includes(this.searchKey.toLowerCase())
    //   )
    // }
  },

  methods: {
    handleSearch() {
      this.currentPage = 1 // 搜索时重置到第一页
      this.loadAppData()
    },
    // 加载数据方法
    async loadAppData() {
      try {
        const params = {
          page: this.currentPage,
          size: this.pageSize,
          keywords: this.searchKey,
        }

        const {data} = await queryApiPage(params)
        this.appList = data.records
        this.total = data.total
        // 同步分页信息（根据接口实际情况调整）
        this.currentPage = data.current
        this.pageSize = data.size
      } catch (error) {
        console.error('数据加载失败:', error)
      }
    },
    handleCreate() {
      this.isEdit = false
      this.createAppForm = {}
      this.dialogVisible = true
    },

    handleEdit(row) {
      this.isEdit = true
      this.createAppForm = {
        id: row.id,
        name: row.name,
        api: row.api,
        remark: row.remark,
        method: row.method
      }
      this.dialogVisible = true

    },

    handleDelete(row) {
      this.$confirm('确认删除该接口池吗？', '提示', {
        type: 'warning'
      }).then(() => {
        // 执行删除操作
        delApi({id: row.id}).then(res => {
          this.$message.success('删除成功')
          this.loadAppData()
        })
      })
    },
    confirmSubmit() {
      this.$refs.form.validate(async valid => {
        if (valid) {
          try {
            if (this.isEdit) {
              await updateApi({
                id: this.createAppForm.id,
                name: this.createAppForm.name,
                api: this.createAppForm.api,
                remark: this.createAppForm.remark,
                method: this.createAppForm.method
              })
            } else {
              await createApi(
                  {
                    name: this.createAppForm.name,
                    api: this.createAppForm.api,
                    remark: this.createAppForm.remark,
                    method: this.createAppForm.method
                  }
              );
            }
            this.$message.success(this.isEdit ? '修改成功' : '创建成功')
            this.dialogVisible = false
            this.loadAppData()
          } catch (e) {

          } finally {

          }
        }
      })
    },

    handleSizeChange(val) {
      this.pageSize = val
      this.currentPage = 1
    },

    handlePageChange(val) {
      this.currentPage = val
    }
  }
}
</script>

<style scoped>
.interface-pool-container {
  padding: 20px;
  background: #fff;
  min-height: calc(100vh - 60px);
}

.operation-bar {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.el-table {
  margin-top: 15px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.el-pagination {
  margin-top: 20px;
  padding: 10px 0;
  background: #fff;
  border-radius: 4px;
}
</style>